<!-- 组织绑定 -->
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import type { IDbAction, IDbTable } from '@/types/global'
import useNotic from '@/hooks/useNotic'
import * as orgApi from '@/api/org'
import { ENUM_BTN_AUTH_SYS } from '@/config/btn'

defineProps({
  title: {
    type: String,
    default: '绑定组织'
  }
})
// 弹窗数据
const showDialog = ref(false)

// 表格数据
const tableData = reactive<IDbTable>({
  columns: [
    { label: '序号', type: 'index', prop: '', width: '60px' },
    { label: '原组织', prop: 'sourceOrgName', minWidth: '200px' },
    { label: '绑定组织', prop: 'targetOrgName', minWidth: '200px' },
    { label: '操作', prop: 'handle', fixed: 'right', type: 'slot', width: '100px' }
  ],
  data: [],
  search: {
    pageNum: 1,
    pageSize: 20,
    sourceOrgId: ''
  }
})

/**
 * 获取表格数据
 */
function getDataList() {
  orgApi.getBindListByPage(tableData.search).then((res) => {
    if (res.success) {
      tableData.data = res.data.rows
      tableData.total = res.data.total
    }
  })
}

/**
 * 点击删除
 */
function delClick(scoped: any) {
  useNotic().confirm(`您确定要删除第<${scoped.$index + 1}>个绑定关系吗？`, (flag) => {
    if (flag) {
      orgApi.delOrgBind(scoped.row.id).then((res) => {
        if (res.success) {
          useNotic().success('删除成功')
          getDataList()
        }
      })
    }
  })
}
/**
 * 设置表格按钮
 */
function setBtnList(scoped: any) {
  const list: IDbAction[] = [
    { label: '删除', type: 'danger', auth: ENUM_BTN_AUTH_SYS['组织管理:绑定'], onClick: () => delClick(scoped) }
  ]
  return list
}
/**
 * 选中组织回调
 */
function pickEvt(curNode: any) {
  if (curNode.id == tableData.search!.sourceOrgId) {
    useNotic().warning('不能绑定自身')
    return
  }
  // TODO 请求绑定
  orgApi.addOrgBind({ sourceOrgId: tableData.search!.sourceOrgId, targetOrgId: curNode.id }).then((res) => {
    if (res.success) {
      useNotic().success('绑定成功')
      getDataList()
    }
  })
}
/**
 * 初始化弹窗
 */
function init(id: string) {
  tableData.search!.pageNum = 1
  tableData.search!.pageSize = 20
  tableData.search!.sourceOrgId = id
  showDialog.value = true
  getDataList()
}

defineExpose({
  init
})
</script>

<template>
  <dui-dialog v-model="showDialog" :title="title">
    <dui-page :search-data="tableData.search" @search="getDataList">
      <template #btn>
        <DbPickOrg @pick="pickEvt">
          <el-button type="primary"> 添加绑定 </el-button>
        </DbPickOrg>
      </template>
      <template #default>
        <dui-table
          :data="tableData.data"
          :columns="tableData.columns"
          :total="tableData.total"
          :search="tableData.search"
          row-key="id"
          @search="getDataList"
        >
          <template #handleSlot="scoped">
            <dui-action :list="setBtnList(scoped)" />
          </template>
        </dui-table>
        <!-- 弹窗 -->
      </template>
    </dui-page>
    <template #footer>
      <el-button @click="showDialog = false">关闭</el-button>
    </template>
  </dui-dialog>
</template>
